// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const voiceCollection = db.collection('voice')
const userCollection = db.collection('user')
const likeCollection = db.collection('liker_liked')
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  let voiceList = []
  const page = event.page || 1
  const pageSize = event.pageSize || 10
  const currentPage = (page - 1) * pageSize
  const wxContext = cloud.getWXContext()

  await likeCollection.where({
    likerOpenId: wxContext.OPENID,
    likedOpenId: _.neq(wxContext.OPENID)
  }).orderBy('likeDate', 'desc')
  .skip(currentPage).limit(pageSize).field({
    likedVoiceId: true,
    likedOpenId: true
  }).get().then(res => {
    voiceList = res.data
  })
    for (let item of voiceList){
      await voiceCollection.doc(item.likedVoiceId).get().then(res => {
        item.voice = res.data
      })

      await userCollection.where({
        _openid: item.likedOpenId
      }).get().then(res => {
        item.userInfo = res.data[0]
      })

      // await likeCollection.where({
      //   likerOpenId: wxContext.OPENID,
      //   likedVoiceId: item._id
      // }).count().then(count => {
      //   if(count.total == 0){
      //     item.isLike == false
      //   }else{
      //     item.isLike = true
      //   }
      // })
  }
  return voiceList
}